package com.css.fxfzaqbz.zcpt.sys.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzaqbz.base.response.RestResponse;
import com.css.fxfzaqbz.constants.FxfzConstants;
import com.css.fxfzaqbz.util.CreateGson;
import com.css.fxfzaqbz.util.PlatformObjectUtils;
import com.css.fxfzaqbz.util.ResponseCreator;
import com.css.fxfzaqbz.zcpt.sys.entity.ReturnAreaTree;
import com.css.fxfzaqbz.zcpt.sys.entity.vo.OrgVO;
import com.css.fxfzaqbz.zcpt.sys.service.SysOrgService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Dbj
 * @date 2022年08月10日  11:17
 */
@RestController
@RequestMapping("/fxfz/sOrg")
@Slf4j
public class SysOrgController {
    @Autowired
    private SysOrgService sysOrgService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 获取全部组织机构树
     */
    @GetMapping("/jsonSOrgToDeptTree")
    public RestResponse jsonSOrgToDeptTree(@RequestParam("orgId") String orgId) {
        RestResponse restResponse = null;
        try{
            String jsonStr = sysOrgService.jsonSOrgToDeptTree(orgId);
            Gson gson = CreateGson.createGson();
            List sysMenuList = gson.fromJson(jsonStr, List.class);
            restResponse = RestResponse.succeed(sysMenuList);
        }catch (Exception e){
            log.error("查询机构失败!",e);
            restResponse = RestResponse.fail("查询机构失败!");
        }
        return restResponse;
    }

    /**
     * 根据父节点ID获取组织机构树
     */
    @GetMapping("/listOrgTree")
    public RestResponse listOrgTree(@RequestParam("orgId") String orgId) {
        RestResponse restResponse = null;
        try{
            long start = System.currentTimeMillis();
            ReturnAreaTree tree = sysOrgService.listOrgTree2(orgId);
            restResponse = RestResponse.succeed(tree);
            long end = System.currentTimeMillis();
            long l = TimeUnit.MILLISECONDS.toSeconds(end - start);
            System.out.println(l);
        }catch (Exception e){
            log.error("查询机构失败!!",e);
            restResponse = RestResponse.fail("查询机构失败!!");
        }
        return restResponse;
    }

    /**
     * 根据父节点ID获取组织机构树
     * parentId=0 显示国家级
     *        =国家级id 显示省级
     *        = 省级id  显示市级
     *        = 市级id 显示区县级
     */
    @GetMapping("/getOrgData")
    public RestResponse getOrgData(@RequestParam("parentId") String parentId) {
        RestResponse restResponse = null;
        try{
            String jsonStr = sysOrgService.getOrgDataByParentId(parentId);
            Gson gson = CreateGson.createGson();
            List sysMenuList = gson.fromJson(jsonStr, List.class);
            restResponse = RestResponse.succeed(sysMenuList);
        }catch (Exception e){
            log.error("查询机构失败!",e);
            restResponse = RestResponse.fail("查询机构失败!");
        }
        return restResponse;
    }

    /**
     * 级联机构
     */
    @GetMapping("/getOrgTree")
    public RestResponse getOrgTree() {
        RestResponse restResponse = null;
        Gson gson = CreateGson.createGson();
        String jsonStr = redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  + "orgList");
        Object parse = JSONArray.parse(jsonStr);
        List<JSONObject> sysOrgList = JSONObject.parseArray(jsonStr,JSONObject.class);
        List<OrgVO> children =new ArrayList<>();
        if(sysOrgList!=null && sysOrgList.size()>0){
            for(int i=0;i<sysOrgList.size();i++){
                JSONObject map =(JSONObject)  sysOrgList.get(i);
                String name = map.get("name").toString();
                if(name.equals("北京市") || name.equals("天津市") || name.equals("上海市") || name.equals("重庆市") ){
                    if(map.get("divisionLevel").equals("2")){
                        OrgVO vo = new OrgVO();
                        vo.setValue(map.get("id").toString());
                        vo.setLabel(map.get("name").toString());
                        free(map.get("id").toString(),sysOrgList,vo);
                        children.add(vo);
                    }
                }else if(map.get("pId").equals("0")){
                    OrgVO vo = new OrgVO();
                    vo.setValue(map.get("id").toString());
                    vo.setLabel(map.get("name").toString());
                    free(map.get("id").toString(),sysOrgList,vo);
                    children.add(vo);
                }
            }
        }
        String s = CreateGson.createGson().toJson(children);
        return RestResponse.succeed(JSONObject.parse(s));
    }

    void free(String id, List trees, OrgVO root){
        List<OrgVO> children =new ArrayList<>();
        for (int i =0; i < trees.size(); i++) {
            JSONObject map = (JSONObject) trees.get(i);
            if (map.get("pId").equals(id)) {
                OrgVO root1 = new OrgVO();
                root1.setValue(map.get("id").toString());
                root1.setLabel(map.get("name").toString());
                Boolean isLeaf =Boolean.valueOf(map.get("isLeaf").toString());
                if(isLeaf){
                    children.add(root1);
                    //leaf=2;
                }else{
                    free(root1.getValue(), trees, root1);
                    children.add(root1);
                }
            }
        }
        root.setChildren(children);
    }

    /**
     * 获取机构信息
     */
    @GetMapping("/getOrgById")
    public RestResponse getOrgById(@RequestParam("orgId") String orgId) {
            String orgJson = sysOrgService.getOrgById(orgId);
            JSONObject jsonObject =(JSONObject) JSONObject.parse(orgJson);
            return ResponseCreator.createSuccessResponse(jsonObject);
    }
    /**
     * 获取机构信息
     */
    @GetMapping("/getOrgByIds")
    public RestResponse getOrgByIds(@RequestParam("orgIds") String orgIds) {
        String[] orgIdList = orgIds.split(",");
        List<JSONObject> jsonObjects = new ArrayList<>();
        for (String orgId : orgIdList) {
            String orgJson = sysOrgService.getOrgById(orgId);
            JSONObject jsonObject =(JSONObject) JSONObject.parse(orgJson);
            if (PlatformObjectUtils.isNotEmpty(jsonObject)){
                jsonObjects.add(jsonObject);
            }
        }

        return ResponseCreator.createSuccessResponse(jsonObjects);
    }
}
